﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ChholCmdPort {
	public class PortChecker {
		static public (bool avaliable, string warning) check(Cc9d.Cc9dCodec test_codec) {
			AutoResetEvent handshake_recv_event = null; 
			try {
				handshake_recv_event = new AutoResetEvent(false);
				var pkg = new Pkg();
				pkg.From_port = 88;
				pkg.To_port = 102;
				pkg.Remote_addr = 0xfff0;
				//这一部分属于应用层协议，不属于CC9D
				byte[] data = { (byte)'H', (byte)'f', (byte)'i', (byte)'n', (byte)'d' };
				pkg.loadData(data);
				test_codec.dRecvPkg = _bp => {
					var recv_pkg = new Pkg(_bp);
					if (recv_pkg.Remote_addr != 0xfff0) return;
					if (recv_pkg.From_port != 102) return;
					if (recv_pkg.To_port != 88) return;
					if (recv_pkg.Data_len != 5) return;
					if (recv_pkg[0] != (byte)'h') return;
					if (recv_pkg[1] != data[1]) return;
					if (recv_pkg[2] != data[2]) return;
					if (recv_pkg[3] != data[3]) return;
					if (recv_pkg[4] != data[4]) return;
					handshake_recv_event?.Set();
				};
				test_codec.send(pkg.cc9d_pkg);
				if (handshake_recv_event.WaitOne(200) == true) {
					handshake_recv_event.Dispose();
					handshake_recv_event = null;
					return (true, "");
				} else {
					handshake_recv_event.Dispose();
					handshake_recv_event = null;
					return (false, "没有收到握手信号；");
				}
			} catch (System.Exception e) {
				handshake_recv_event?.Dispose();
				handshake_recv_event = null;
				return (false, e.Message);
			}

		}
	}
}
